<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :title="$t('mexico.finishedWarehouse')" scanType="0"></nav-bar-custom>
		</template>

		<template v-slot:gBody>
			<view class="distributed">
				<view class="gui-bg-white gui-dark-bg-level-3 gui-padding-x distributed-head">
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="gui-form-label gui-secondary-text">{{ $t('distributedOut.warehouse') }}</text>
						<input class="uni-input" v-model="data.warehouseCode" style="text-align: right;" disabled />
					</view>
					<view class="custom-card-itemTwo " style="padding: 20rpx 0;">
						<text class="gui-form-label gui-secondary-text">{{
							$t('distributedOut.location') }}：</text>
						<!-- 有容量的库位 -->
						<comboGrid requestUrl="/api1/wms/warehouse/QueryLocation" v-model="data.locationCode"
							:requestParam="data.requestParam" inputKey="locationCode" :calculate="false"
							:placeholder="$t('distributedEnter.placeholderTextChoose')"
							:gridPlaceholder="$t('pageTranslation.plsInputFilter')" :column="data.columnLocation.column"
							bindValue="locationCode" @setClick="getLocationClick"></comboGrid>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="gui-form-label gui-secondary-text">{{ $t('Common.pointPosition') }}：</text>
						<comboGrid requestUrl="/api1/wms/instock/GetLocationPointDetail" v-model="data.agvPointCode"
							:requestParam="data.positionParam" inputKey="agvpointcode" :calculate="false"
							:placeholder="$t('distributedEnter.placeholderTextChoose')"
							:gridPlaceholder="$t('Common.enterCodeOrName')" :column="data.columnName.column"
							bindValue="agvpointcode" @setClick="gePositionClick">
						</comboGrid>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;" v-if="data.whichNumber">
						<text class="gui-form-label gui-secondary-text">{{ $t('mexico.position') }}</text>
						<input class="uni-input" v-model="data.whichNumber" style="text-align: right;" disabled />
					</view>
					<view class="gui-form-item gui-border-b gui-flex gui-justify-content-center">
						<view class="gui-flex gui-space-between gui-align-items-center"
							style="width: 70%;height: 100rpx;">
							<button type="default" class="gui-button gui-button-mini gui-bg-black4 gui-noborder"
								style="width:200rpx;" @click="reset(OPERATION_REASCT)">
								<text class="gui-block gui-color-black gui-button-text-mini gui-icons">{{
									$t('distributedEnter.reset') }}</text>
							</button>
							<button type="default" class="gui-button gui-button-mini gui-bg-blue gui-noborder"
								style="width:200rpx;" @click="search">
								<text class="gui-block gui-color-white gui-button-text-mini gui-icons">{{
									$t('distributedEnter.search') }}</text>
							</button>
						</view>
					</view>
				</view>
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6"
						style="padding-left:50rpx; padding-right:50rpx;">{{ $t('translationImage.materialsInformation')
						}}</text>
					<view class="gui-title-line"></view>
				</view>
				<!-- 底部显示区域 -->
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll" @scrolltolower="scrolltolower">
					<view style="height: 15rpx"></view>
					<view class="record-card" v-for="(list, index) in data.list" :key="index"
						@click.stop="checkboxChange(list)">
						<!-- <uni-icons class="close-icons" type="closeempty" color="#9C9C9C" size="30"
							@click="deletList(index, list)"></uni-icons> -->
						<view class="card-mini-head">
							<view class="title-line"></view>
							<text>{{ $t('translationImage.serialNumber') }}：{{ index + 1 }}</text>
							<view style="flex:1;text-align: right;">
								<checkbox-group @change="checkboxChange(list)">
									<checkbox value="1" :checked="list.checkbox" />
								</checkbox-group>
							</view>
						</view>
						<view class="custom-card-itemOne">
							<text class="item-info-title">{{ $t('distributedEnter.materialCoded')
								}}：</text>{{ list.barcode }}
						</view>
						<view class="custom-card-itemOne">
							<text class="item-info-title">{{ $t('distributedEnter.materialCode')
								}}：</text>{{ list.materialCode }}
						</view>
						<view class="custom-card-itemOne">
							<text class="item-info-title">{{ $t('distributedEnter.materialName')
								}}：</text>{{ list.materialName }}
						</view>
						<view class="custom-card-itemOne">
							<text class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{ list.spec
							}}
						</view>
						<view class="custom-card-itemOne">
							<view class="card-item-50">
								<text class="item-info-title">{{ $t('distributedEnter.qty') }}：</text>{{ list.currentQty
								}}
							</view>
							<view class="card-item-50">
								<text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{ list.unit }}
							</view>
						</view>
						<view class="custom-card-itemOne">
							<view class="card-item-50">
								<text class="item-info-title">{{ $t('distributedOut.warehouse')
									}}：</text>{{ 'FG' }}
							</view>
							<view class="card-item-50">
								<text class="item-info-title">{{ $t('distributedOut.location')
									}}：</text>{{ list.locationCode }}
							</view>
						</view>
						<view class="custom-card-itemOne">
							<view class="card-item-50">
								<text class="item-info-title">{{ $t('Common.pointPosition') }}：</text>{{
									list.agvPointCode}}
							</view>
							<view class="card-item-50">
								<text class="item-info-title">{{ $t('mexico.position') }}：</text>{{ list.whichNumber }}
							</view>
						</view>
						<view class="custom-card-itemOne gui-flex gui-justify-content-end">
							<view class="card-item-50" style="text-align: right;">
								<view class="print-class" @click.stop="handelPrint(list)">
									{{ $t('multilingual.printBarcode') }}
								</view>
							</view>
						</view>
					</view>
					<view v-if="data.noticeHooks" class="noticeHooks">
						{{ data.list.length == 0 ? $t('stockManage.notAvailable') : $t('stockManage.without') }}
					</view>
				</scroll-view>
				<!-- 底部确定按钮 -->
				<view class="page-bottom-box">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelCommit">
						{{ $t('multilingual.print') }}</view>
				</view>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import pdaScan from '@/hooks/pdaScan.js'
import { useStore } from "vuex";
import { } from '@/constant/index.js'
import { getDataDictionaryFn } from '@/utils/index.js'
import storageBin from '@/components/storageBin.vue'
import comboGrid from '@/components/comboGrid.vue'
import { onShow } from '@dcloudio/uni-app';
import { basPdaOperationLogFn } from '@/utils/index.js';
import { getFGLocationBarcodeDetail, printFGBarcode } from '@/api/api.js'
import { ref, reactive, onMounted, watch, computed, toRaw } from 'vue';
import { OPERATION_SEARCH, OPERATION_REASCT, OPERATION_COMMIT, OPERATION_LOOK, OPERATION_CHOOSE, OPERATION_SCAN, OPERATION_SURE, BIGBARCODER_PRINT } from '@/constant/index.js'

//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

components: {
	storageBin,
		comboGrid
}
const storageBinRef = ref(null)
const comboGridRef = ref(null)

const { scan } = pdaScan()
let store = useStore();

const navHeight = computed(() => {
	return store.state.navHeight
})

let data = reactive({
	warehouseCode: 'FG',
	locationCode: '',//目的库位
	whichNumber: 0,// 位置
	agvPointCode: '',//点位
	focus: true,
	// 库位数据获取
	requestParam: {
		warehouseId: 0, // 设置的默认仓库
		warehouseName: '',
		warehouseCode: 'FG',
		locationCode: "",
		locationName: '',
		locationTypeCode: '',
		locationTypeName: '',
		forbiddenStatus: '',
		areaCode: ''
	},
	columnLocation: {
		column: [{
			label: t('JsInternational.volumnStockName'),
			name: "locationName",
		}, {
			label: 'code',
			name: "locationCode",
		}]
	},
	//点位获取
	positionParam: {
		warehouseCode: 'FG',
		locationCode: '',
		whichNumber: 0,
		agvpointcode: ''
	},
	//物料代码下面的筛选
	columnName: {
		column: [{
			label: t('Common.pointPosition'),
			name: "agvPointCode",
		}, {
			label: t('mexico.position'),
			name: "whichNumber",
		}]
	},
	page: 1,
	rows: 10,
	list: [],
	noticeHooks: false, //暂无相关数据标识
})

onMounted(() => {
	uni.$on('scancodedate', (itme) => {
		console.log('获取到的code：' + itme.code, data.focus)
		if (data.focus) {
			getCodeLocation(itme.code, 'pda')
		}
		if (data.focus == false) {
			getCode(itme.code, 'pda')
		}
	})
	getLocaitonData()
})

//库位选择
const getLocationClick = (x) => {
	data.positionParam.locationCode = x.locationCode
	data.locationCode = x.locationCode
}
// 点位选择
const gePositionClick = (x) => {
	data.agvPointCode = x.agvPointCode
	data.whichNumber = x.whichNumber
}

// 重置
const reset = async (type) => {
	data.locationCode = ''
	data.whichNumber = 0
	data.agvPointCode = ''
	getLocaitonData()
}

//上拉加载
const scrolltolower = () => {
	if (!data.noticeHooks) {
		data.page++
		getLocaitonData()
	}
}

// 查询
const search = () => {
	data.operationType = OPERATION_SEARCH
	data.page = 1
	getLocaitonData()
}

const getLocaitonData = () => {
	let parmase = {
		current: data.page,
		size: data.rows,
		warehouseCode: data.warehouseCode,
		locationCode: data.locationCode,
		whichNumber: data.whichNumber,
		agvPointCode: data.agvPointCode,
	}
	getFGLocationBarcodeDetail(parmase).then(res => {
		try {
			let inputParameter = JSON.stringify(parmase)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '成品库位详情'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SEARCH,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 0) {
			data.noticeHooks = false
			if (data.page === 1) {
				if (res.data.records?.length == 0 || res.data.records === null) {
					data.noticeHooks = true
				}
				data.list = res.data.records || []
				data.list.forEach(element => {
					element.openBool = false
				});
			} else {
				let arr = res.data.records
				arr.forEach(element => {
					element.openBool = false
				});
				data.list = [...data.list, ...arr]

			}
			data.list.forEach(item => {
				item.checkbox = false
			})
			data.noticeHooks = data.list.length >= res.data.total
		}
	})
}

// 打印
const handelPrint = (item) => {
	console.log(item)
	// return
	if (item == null) {
		uni.showToast({ title: t('stockManage.pleaseScanCode'), icon: "none" });
		return
	}
	let defaultValue = uni.getStorageSync(BIGBARCODER_PRINT) || ''
	if (defaultValue == '') {
		uni.showModal({
			content: t('JsInternational.plsPrinter'),
			showCancel: false,
			confirmText: t('pageTranslation.toSet'),
			success: function (res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/setting/printer'
					})
				} else if (res.cancel) {

				}
			}
		});
		return
	}
	let parmase = {
		barCode: item.barcode,
		materialCode: item.materialCode,
		materialName: item.materialName,
		specification: item.materialSpec,
		LocationCode: item.locationCode,
		produceDate: item.produceDate ? item.produceDate.slice(0, 10) : '', // 生产日期
		hostid: item.equipmentCode || '', //机台
		qty: item.currentQty,
		uuit: item.unit, //单位
		printIp: '',
		printName: defaultValue //打印机名字
	}
	console.log(parmase)
	uni.showLoading({
		title: t('materials.connecting')
	});
	printFGBarcode(parmase).then(res => {
		try {
			let inputParameter = JSON.stringify(parmase)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '库位条码详情'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_PRINT,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		uni.hideLoading();
		if (res.code == 0) {
			uni.showToast({ title: t('JsInternational.printSuccessfully'), icon: "none" });
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
}

// 选择checkboxChange
const checkboxChange = (item) => {
	console.log(item)
	// item.checkbox=!item.checkbox
	data.list.forEach(a => {
		if (item.barcode == a.barcode) {
			item.checkbox = !item.checkbox
		}
	})
}

// 批量打印
const handelCommit = () => {
	let arr = data.list.filter(x => x.checkbox == true)
	if (!data.list.length || !arr.length) {
		uni.showToast({ title: t('mexico.seletcDataPlease'), icon: "none" });
		return
	}
	let defaultValue = uni.getStorageSync(BIGBARCODER_PRINT) || ''
	if (defaultValue == '') {
		uni.showModal({
			content: t('JsInternational.plsPrinter'),
			showCancel: false,
			confirmText: t('pageTranslation.toSet'),
			success: function (res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/setting/printer'
					})
				} else if (res.cancel) {

				}
			}
		});
		return
	}
	function testPromise(item) {
		return new Promise((resolve, reject) => {
			let parmase = {
				barCode: item.barcode,
				materialCode: item.materialCode,
				materialName: item.materialName,
				specification: item.materialSpec,
				LocationCode: item.locationCode,
				produceDate: item.produceDate ? item.produceDate.slice(0, 10) : '', // 生产日期
				hostid: item.equipmentCode || '', //机台
				qty: item.currentQty,
				unit: item.unit, //单位
				printName: defaultValue, //打印机名字
			}
			console.log(parmase)
			printFGBarcode(parmase).then(res => {
				try {
					let inputParameter = JSON.stringify(parmase)
					let returnParameter = JSON.stringify(res)
					let operationPicture = '成品库位明细'
					let callInterface = printUrl + '/print/barCodePrint'
					let opertionParmes = {
						inputParameter,
						returnParameter,
						operationPicture,
						callInterface,
						responseCode: res.code,//返回状态
						errorMessage: res.msg,//错误信息
						isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
						operationType: OPERATION_SURE
					}
					basPdaOperationLogFn(opertionParmes)
				} catch (error) {
				}
				console.log(res, 'reessss')
				uni.hideLoading();
				if (res.code == 0) {
					//打印成功之后调用保存
					uni.showToast({ title: t('JsInternational.printSuccessfully'), icon: "none" });
					resolve(item);
				} else {
					data.printSuccessFlag = false;
					uni.showToast({ title: res.msg, icon: "none" });
					reject()
				}
			})
		});
	}
	let result = arr.reduce((accumulatorPromise, item) => {
		return accumulatorPromise.then(() => {
			return testPromise(item);
		});
	}, Promise.resolve());
	result.then(e => {
		uni.hideLoading();
	});
}

</script>

<style lang="scss" scoped>
.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.noticeHooks {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 80rpx;
	font-size: 32rpx;
	color: #999;
}

.distributed {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.item {
	position: relative;

	.tags {
		position: absolute;
		right: 0;
		top: 0;
	}
}

.print-class {
	display: inline-block;
	padding: 10rpx 20rpx;
	background-color: chartreuse;
	color: #fff;
	border-radius: 8rpx;
	background: $uni-color-teal;
}
</style>
